<template>
  <van-notify v-model:show="show" type="success">
    <van-icon style="margin-right: 4px" />
    <span>打招呼成功!请耐心等待{{ name }}的回应...</span>
  </van-notify>
  <van-search
    v-model="searchMessage"
    shape="round"
    background="DeepSkyBlue"
    show-action
    placeholder="请输入要搜索的用户昵称"
    @search="loadData"
  />
  <div v-if="showHistory">
    <span class="history">
      历史搜索
      <van-icon
        class="delIcon"
        name="delete-o"
        @click.native="clearSearchHistory"
      />
    </span>
    <div>
      <span
        v-for="(item, index) in searchHistoryList"
        :key="index"
        @click="loadData(item)"
        class="searchValBtn"
      >
        <van-button round size="small">{{ item }} </van-button>
      </span>
    </div>
  </div>
  <template v-if="userList && searchFirst === 1">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :offset="130"
      @load="onLoad"
    >
      <user-card-list
        :user-list="userList"
        :loading="loading"
        :show-tag="false"
        isGetUser="1"
        is-detail="0"
        @showNotify="showNotify"
      />
    </van-list>
  </template>
</template>

<script setup lang="ts">
import myAxios from "../plugins/myAxios";
import UserCardList from "../components/UserCardList.vue";
import { UserType } from "../models/user";
import { onMounted, ref, watch } from "vue";
import { showConfirmDialog, showFailToast, showSuccessToast } from "vant";
import { getCurrentUser } from "../services/user";

const show = ref(false); //展示消息通知
const name = ref(""); //反馈打招呼对象的昵称
//展示打招呼的反馈信息，由子组件触发
const showNotify = (showNot: boolean, username: string) => {
  show.value = showNot;
  name.value = username;
  setTimeout(() => {
    show.value = false;
  }, 2500);
};

const searchMessage = ref(""); //搜索框里的内容
const showHistory = ref(true); //是否展示历史搜索
//一旦搜索框为空立刻展示历史搜索
watch(searchMessage, () => {
  if (searchMessage.value.length === 0) {
    showHistory.value = true;
  }
});

const searchHistoryList = ref([]);
// 添加搜索首页历史查询记录
const addSearchHistory = (value: string) => {
  // 过滤一个结果的空记录添加，如果历史搜索为空则直接添加
  if (searchHistoryList.value.length === 0) {
    searchHistoryList.value.push(value);
  } else {
    //删除重复值
    searchHistoryList.value.forEach((element, index) => {
      if (element === value) {
        searchHistoryList.value.splice(index, 1);
      }
    });
    // 添加之后若长度大于10则删除最后一个元素
    if (searchHistoryList.value.unshift(value) > 10) {
      searchHistoryList.value.pop();
    }
  }
  localStorage.setItem("historyItems", JSON.stringify(searchHistoryList.value));
};

// 清除历史搜索
const clearSearchHistory = () => {
  if (searchHistoryList.value.length === 0) return;
  showConfirmDialog({
    message: "确定要清除历史搜索吗？",
  }).then(async () => {
    localStorage.removeItem("historyItems");
    searchHistoryList.value = [];
    showSuccessToast({
      message: "小智暖心提醒:清除成功",
      position: "bottom",
    });
  });
};

const userList = ref([]); //展示用户
const userListData = ref([]); //接收后端的数据
const loading = ref(false); //是否处于加载状态
const finished = ref(false); //是否加载完成
const searchFirst = ref(0); //至少有一次有效搜索之后再展示用户卡片
const loadData = async (value: string) => {
  if (value.trim()) {
    addSearchHistory(value); //存入历史搜索中
    showHistory.value = false;
    searchMessage.value = value;
  }
  if (!searchMessage.value.trim()) {
    showFailToast("小智遗憾告知:搜索内容不能为空");
    return;
  }
  searchFirst.value = 1;
  //重置信息，防止受上一次搜索结果的影响
  finished.value = false;
  userList.value = [];
  userListData.value = await myAxios
    .get("/user/search", {
      params: {
        searchMessage: searchMessage.value,
      },
    })
    .then(function (response) {
      return response?.data;
    })
    .catch(function () {
      showFailToast("小智遗憾告知:请求失败!!请刷新重试");
    });
  if (userListData.value.length !== 0) {
    onLoad();
  } else {
    finished.value = true;
  }
};

const myFriendIdList = ref([]); //所有好友的id列表
const onLoad = () => {
  if (userListData.value.length !== 0) {
    const userArr = userListData.value.splice(0, 8); //过渡的数组
    if (userListData.value.length === 0) {
      finished.value = true;
    }
    userArr.forEach((user: UserType) => {
      if (user.tags) {
        user.tags = JSON.parse(user.tags);
      }
      if (myFriendIdList.value.find((id) => id === user.id)) {
        user.isMyFriend = true;
      }
      userList.value.push(user);
    });
  }
};

const currentUser = ref({} as UserType); //当前用户
onMounted(async () => {
  // 获取历史搜索信息
  if (localStorage.historyItems) {
    const historyItemsStr = localStorage.getItem("historyItems");
    searchHistoryList.value = historyItemsStr && JSON.parse(historyItemsStr);
  }
  currentUser.value = await getCurrentUser("1");
  await myAxios
    .get("/user/myFriendId", {
      params: {
        userId: currentUser.value.id,
      },
    })
    .then((res) => {
      if (res.code === 0 && res.data) {
        myFriendIdList.value = res.data;
      }
    });
});
</script>

<style scoped>
@import "../assets/css/search.css";
</style>
